<template>
	<view :class="currentTheme">
		<a-nabbar name="结算" />
		<view class="u-padding-32">
			<item-box @click.native="selectAddress" v-if="option.type!='ticket'" :padding="32">
				<view class="u-text-center" v-if="!showAddress">
					<view class="empty-icon u-flex u-row-center">
						<u-icon name="plus" size="30" :color="currentThemeObj.primary"></u-icon>
					</view>
					<view class="text-color-DEDEDE u-font-30 u-margin-top-30">暂无地址，请添加</view>
					<!-- <u-icon name="arrow-right" size="36" color="#6C50FE"></u-icon> -->
				</view>
				<view class="u-flex u-row-between" v-else>
					<view class="u-flex-1">
						<vAddress :item="address"></vAddress>
					</view>
					<u-icon name="arrow-right" size="36" color="#333333" class="u-margin-left-20"></u-icon>
				</view>
			</item-box>
			<view class="u-margin-top-20 data-list" v-for="(item,index) in dataList" :key="index">
				<item-box :padding="36">
					<view>
						<!-- <view class="u-font-20 text-color-B0B2D8 u-margin-top-10 u-margin-bottom-10 u-padding-14">发行名：{{item.name}}</view> -->
						<!-- <list-item :item="{...val,hotelAddress:''}" :isTag="false" :showStar="false" 
							v-for="(val,i) in item.list" :key="i" :isShare="false"  width="158" height="158">
							<view slot="content" class="u-font-20 text-color-B0B2D8 u-margin-top-24"></view>
							<view class="u-flex space-between u-flex-1" slot="footer">
								<template v-if="!isGroupBuy">
									<view class="u-flex">
										<text class="text-bold u-font-36 text-color-765CFE">￥{{val.exhibitPrice || 0}}</text>
									</view>
									<view class="text-color-B0B2D8 u-font-26" v-if="val.num===0">该商品不可购买</view>
									<view v-else class="text-white">
										<numberBox v-model="val.num" :num='val.num'
										:index="i"
										:min="1" :max="val.grantNumber || 99999" 
										@change="getInputChange" 
										 bgColor="rgb(31, 27, 52)" color="#765CFE" />
									</view>
								</template>
								<template v-if="isGroupBuy">
									<view class="u-font-30 text-color-765CFE">x{{val.num}}</view>
								</template>
							</view>
						</list-item> -->
						<!-- <view class="u-flex u-padding-left-25 u-padding-right-25  space-between align-center empty-address"  
						v-if="!isGroupBuy">
							<text class="text-color-DEDEDE u-font-28 u-margin-right-10">留言</text>
							<view class="u-flex-1 diy-input">
								<u-input v-model="item.mark" placeholder="给商家留言" input-align="right" :clearable="false" class="text-color-DEDEDE" maxlength="30"></u-input>
							</view>
						</view> -->
						<view class="u-margin-bottom-40 u-flex u-row-between">
							<view class="scroll-view u-flex-1">
								<scroll-view scroll-x :scroll-y="false">
									<view class="u-flex">
										<view v-for="(val,i) in item.list" :key="i"
											class="u-margin-right-12 u-position-relative" @click="preview(item.list,i)">
											<item-image :img="val.image" width="158" height="158"></item-image>
											<view v-if="val.type==='1111'" class="double-eleven u-position-absolute">
												<item-image
													img="https://larp-gbo.oss-cn-chengdu.aliyuncs.com/wx/1111tag.png"
													:width="60" :height="30" :radius="0"></item-image>
											</view>
											<view class="productNum u-position-absolute box-title u-font-20">{{val.productNum}}</view>
										</view>
									</view>
								</scroll-view>
							</view>
							<view class="u-flex u-margin-left-12">
								<text class="text-order-time u-font-22 u-margin-right-28">共{{count}}件</text>
								<!-- <u-icon name="arrow-right" size="36" color="#3333333"></u-icon> -->
							</view>
						</view>
						<view class="u-margin-left-14 u-margin-right-14">
							<view class="u-flex u-row-between  u-margin-top-16" v-if="isDeposit">
								<text class="u-font-30">预付定金金额：</text>
								<text class="u-font-32">￥{{totalDeposit}}</text>
							</view>
							<view class="u-flex u-row-between u-margin-top-16">
								<text class="u-font-30 box-title">商品金额：</text>
								<money :price="totalCost" size="36"></money>
							</view>
							<view class="u-flex u-row-between text-tips u-margin-top-16">
								<text class="u-font-24">运费 (运重：10.00 kg)：</text>
								<money :price="0" size="36" color="#808080"></money>
							</view>
							<view class="u-flex text-color-DEDEDE u-margin-top-16 u-col-top" v-if="activityDesc">
								<text class="u-font-24">备注：</text>
								<text class="u-font-24 u-flex-1 text-color-B0B2D8">{{activityDesc}}</text>
							</view>
							<!-- <view class="u-text-right u-margin-top-50 u-margin-bottom-22">
								<text class="text-color-DEDEDE">已优惠：</text><text
									class="text-color-765CFE u-font-36">￥{{calcPrice}}</text>
							</view> -->
						</view>
					</view>
				</item-box>
			</view>
		</view>
		<fixed-team>
			<view class="u-flex-1 u-flex u-row-between">
				<view class="u-flex u-col-top">
					<view>
						<text class="color-80 u-font-20">共{{count}}件商品,</text>
						<text class="box-title text-bold u-font-32">合计：</text>
					</view>
					<view>
						<money :price="totalPriceNum" size="40" :color="currentThemeObj.primary"></money>
						<view class="u-font-20 text-color-txtTheme">
							已优惠:￥{{calcPrice}}
						</view>
					</view>
				</view>
				<view class="u-padding-left-64">
					<item-btn @click="onSubmit" width="268" height="88">{{isGroupBuy ? '提交订单':'去支付'}}</item-btn>
				</view>
			</view>
		</fixed-team>
	</view>
</template>

<script>
	import vAddress from '@/pagesA/acomponents/address/address.vue'
	import {
		getDetail,
		getList,
		add,
		customRequest
	} from '@/api/crud.js'
	import {
		mapGetters
	} from 'vuex'
	import {
		BigNumber
	} from "bignumber.js";
	import loginMixins from '@/pagesA/login/login.js'
	import numberBox from '@/components/numberBox/numberBox.vue'
	export default {
		mixins: [loginMixins],
		components: {
			vAddress,
			numberBox
		},
		data() {
			return {
				showAddress: false,
				dataList: [],
				address: {},
				apiType: 'storeOrder',
				apiModule: 'shopApi',
				count: 0,
				totalPriceNum: 0,
				option: {},
				totalCost: 0,
				calcPrice: 0,
				activityDesc: "",
				isDeposit: false, //是否为定金商品
				totalDeposit: '' //定金金额
			};
		},
		computed: {
			...mapGetters(['loginForm']),
			isGroupBuy() {
				return this.option.type === 'groupBuy'
			},
			cartInfoList() {
				const cartInfoList = []
				this.dataList.forEach(val => {
					val.list.forEach(item => {
						cartInfoList.push({
							productId: item.productId,
							productNum: item.num,
							mallProductId: item.mallProductId,
							experienceProductId:item.experienceProductId,
							mark: val.mark
						})
					})
				})
				return cartInfoList
			}
		},
		onLoad(option) {
			uni.$on('select', res => {
				this.showAddress = true;
				this.address = res;
			})
			this.option = option;
			getDetail(option, this.apiType, this.apiModule, 'getTemp').then(res => {
				res.forEach(item => {
					item.list = item.list.map(val => {
						const cartInfo = JSON.parse(val.cartInfo)
						this.count += val.productNum
						val.num = val.grantNumber || val.productNum || 1
						return {
							...val,
							...cartInfo
						};
					})
				});
				const dataObj = res.reduce((item, next) => {
					item.list = [...item.list, ...next.list]
					return item
				}, {
					list: []
				})
				this.dataList = [dataObj];
				this.getInputChange()
			})
			//获取默认地址
			getList({
				uid: this.loginForm.uid
			}, 'userAddress', 'shopApi', 'list').then(res => {
				const address = res.find(val => val.isDefault);
				this.address = address || {};
				this.showAddress = !!address;
			})
			uni.$on('payMoney', res => {
				console.log(res)
				uni.hideLoading()
				res.uid == this.loginForm.uid && this.navtoFlag(1)
			})
		},
		destroyed() {
			uni.$off('payMoney')
			uni.$off('select')
		},
		methods: {
			//获取当前总价
			getInputChange(e) {
				// this.totalPriceNum = 0;
				// const initialValue = 0;
				// this.totalPriceNum = this.dataList.reduce((total,next)=>{
				// 	const totalPrice = BigNumber(this.totalPrice(next))
				// 	const plus = totalPrice.plus(total)
				// 	return plus.toNumber();
				// },initialValue)
				this.calculateOrderMoney()
			},
			// 获取当前订单的价格 不用自己算了
			async calculateOrderMoney() {
				const data = await add({
					cartInfoList: this.cartInfoList
				}, 'storeOrder', this.apiModule, 'calculateOrderMoney')
				this.totalPriceNum = data.totalPrice // 优惠后的付款价格
				this.totalCost = data.totalCost // 原价
				// this.calcPrice = BigNumber(data.totalCost).minus(data.totalPrice).toNumber() // 优惠价格
				this.calcPrice = BigNumber(data.totalDiscount).toNumber();
				this.activityDesc = data.activityDesc
				this.isDeposit = data.isDeposit; //是否为定金商品
				this.totalDeposit = data.totalDeposit //定金金额
			},
			async onSubmit() {
				if (!this.totalPriceNum) {
					this.$u.toast('支付金额为0不能购买')
					return false
				}

				if (!this.address.realName && this.option.type != 'ticket') {
					this.$u.toast('请先添加收货地址')
					return false;
				}
				//更新预付款订单
				const orderId = await add({
					cartInfoList: this.cartInfoList
				}, 'storeOrder', this.apiModule, 'createTemp')
				const form = {
					cartInfoList: this.cartInfoList,
					orderId,
					isChannel: 1,
					realName: this.address.realName,
					shippingType: 1,
					uid: this.loginForm.uid,
					payType: 'weixin',
					mark: '',
					userAddress: this.address.province + this.address.city + this.address.district + this.address
						.detail,
					userPhone: this.address.phone,
					totalNum: this.count,
					totalPrice: this.totalPriceNum,
					userAddressId: this.address.id
				};
				try {
					await add(form, this.apiType, this.apiModule)
					const code = await this.getLoginCode();
					let codeData = {
						code,
						payType: 'weixin',
						platformType: 'manage'
					}
					const data = await customRequest(codeData, this.apiType, this.apiModule, 'payMoney/' + orderId,
						'post')
					uni.showLoading({
						mask: true,
						title: '支付中...'
					})
					uni.requestPayment({ //微信支付
						provider: 'wxpay',
						...data,
						success: res => {},
						fail: ({
							errMsg
						}) => {
							errMsg === 'requestPayment:fail cancel' ? this.$u.toast('已取消支付') : this
								.navtoFlag(0)
						},
						complete: () => {
							uni.hideLoading()
						}
					});

				} catch (e) {
					//uni.hideLoading()
					// this.navtoFlag(0)
					//TODO handle the exception
				}
			},
			navtoFlag(flag) {
				const title = flag == 1 ? '支付成功' : '支付失败';
				this.$u.toast(title)
				this.$u.route({
					type: "redirectTo",
					url: "/pagesA/success/success",
					params: {
						flag,
						title,
						type: this.option.type
					}
				})
			},
			selectAddress() {
				this.$u.route({
					url: "/pagesB/address/address",
					params: {
						type: 'select'
					}
				})
			},
			totalPrice(item) {
				const initialValue = 0;
				const price = item.list.reduce((total, next) => {
					let {
						exhibitPrice,
						num,
						depositPrice
					} = next;
					exhibitPrice = depositPrice ? BigNumber(depositPrice) : BigNumber(exhibitPrice);
					const plus = exhibitPrice.multipliedBy(num).plus(total)
					return plus.toNumber();
				}, initialValue)
				//this.totalPriceNum +=price
				return price || 0
			},
			//预览
			preview(list, i) {
				const imageList = list.map(val => val.image);
				const current = imageList[i]
				console.log(i)
				this.previewUrls(imageList)
			}
		}
	}
</script>

<style lang="scss" scoped>
	.data-list /deep/ {
		.right-col {
			min-height: auto !important;
		}

		.u-icon-disabled {
			background-color: $primary;
		}

		.u-number-input {
			background: #343142 !important;
			border-radius: 8rpx;
			color: white !important;
		}

		.u-icon-disabled {
			background: none !important;
		}
	}

	.empty-icon {
		border-radius: 50%;
		background: var(--background-color);
		width: 60rpx;
		height: 60rpx;
		line-height: 60rpx;
		margin: 0 auto;
	}

	.scroll-view {
		height: 158rpx;
		width: 62vw;
	}

	.productNum {
		background: #F0F1F5;
		top: 0;
		right: 0;
		padding:7rpx 10rpx;
		border-radius: 0 12rpx;
	}
	.color-80{
		color: #808080;
	}
</style>
